<template>
	<a-form
		ref="formRef"
		name="reservationForm"
		:model="formState"
		:rules="rules"
		v-bind="layout"
		@finish="onFinish"
	>
		<a-form-item name="guestName" label="Name">
			<a-input v-model:value="formState.guestName"></a-input>
		</a-form-item>

		<a-form-item name="contactInfo" label="Contact Info">
			<a-input v-model:value="formState.contactInfo"></a-input>
		</a-form-item>

		<a-form-item name="arrivalTime" label="Expected Arrival Time">
			<a-date-picker
				v-model:value="formState.arrivalTime"
				:format="dateFormat"
				type="date"
				placeholder="Pick a date"
				class="w-full"
			/>
		</a-form-item>

		<a-form-item name="reservedSize" label="Reserve Size">
			<a-input-number v-model:value="formState.reservedSize" class="w-full"></a-input-number>
		</a-form-item>

		<a-form-item :wrapper-col="{ offset: 10, span: 12 }">
			<a-button type="primary" html-type="submit" :loading="loading">Book</a-button>
			<a-button class="ml-2" @click="resetForm">Reset</a-button>
		</a-form-item>
	</a-form>
</template>

<script setup lang="ts">
import { dateFormat } from '@/types/meta';
import type { BookReservationForm } from '@/types/reservation';
import { FormInstance } from 'ant-design-vue';
import { Rule } from 'ant-design-vue/es/form';
import * as dayjs from 'dayjs';
import { UnwrapRef } from 'vue';

// Define
const emits = defineEmits<{
	submit: [value: BookReservationForm];
}>();

withDefaults(defineProps<{ loading: boolean }>(), {
	loading: false,
});

const formRef = ref<FormInstance>();
const formState: UnwrapRef<BookReservationForm> = reactive<BookReservationForm>({
	guestName: '',
	contactInfo: '',
	arrivalTime: dayjs(),
	reservedSize: 0,
});
const layout = {
	labelCol: { span: 10 },
	wrapperCol: { span: 12 },
};

const rules: Record<string, Rule[]> = {
	guestName: [
		{
			required: true,
			message: 'Please input your name',
			trigger: 'change',
		},
		{ min: 2, max: 20, message: 'Length should be 2 to 20', trigger: 'blur' },
	],
	contactInfo: [
		{
			required: true,
			message: 'Please input your contact info',
			trigger: 'change',
		},
	],
	arrivalTime: [
		{
			required: true,
			message: 'Please choose your Expected Arrival Time',
			trigger: 'change',
			type: 'object',
		},
	],
	resource: [
		{
			required: true,
			message: 'Please input your Reserved table Size',
			trigger: 'change',
		},
	],
};

// Action
const onFinish = (value: BookReservationForm) => {
	emits('submit', { ...value, arrivalTime: dayjs(value.arrivalTime).format(dateFormat) });
};

const resetForm = () => {
	formRef?.value?.resetFields();
};
</script>
